package com.example.chatgptapplication.websocket;

import com.baidubce.qianfan.Qianfan;
import com.baidubce.qianfan.core.auth.Auth;
import com.baidubce.qianfan.model.chat.ChatResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.chatgptapplication.entity.Tag;
import com.example.chatgptapplication.entity.User;
import com.example.chatgptapplication.common.Constrants;
import com.example.chatgptapplication.entity.deepseek.DeepSeekRequest;
import com.example.chatgptapplication.exception.MyException;
import com.example.chatgptapplication.relation.UserTag;
import com.example.chatgptapplication.service.DeepSeekService;
import com.example.chatgptapplication.service.TagService;
import com.example.chatgptapplication.service.UserService;
import com.example.chatgptapplication.service.UserTagService;
import com.github.benmanes.caffeine.cache.Cache;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.And;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@ServerEndpoint(value = "/websocket/{userId}")
@Slf4j
@Component
public class WebSocketChannel {


    /***
     * 静态变量，用来记录当前在线连接数
     */
    private static int onlineCount = 0;


    private static ConcurrentHashMap<String,WebSocketChannel> chatWebSocketHashMap = new ConcurrentHashMap<>();


    public static ConcurrentHashMap<String, List<DeepSeekRequest.Message>> chatHistoryHashMap = new ConcurrentHashMap<>();

    private Session session;

    private String userId = "";

    private static UserService userService;


    private static DeepSeekService deepSeekService;


    private static UserTagService userTagService;


    private static TagService tagService;

    private static Cache cache;

    @Autowired
    @Qualifier("caffeineCache")
    public  void setCache(Cache cache) {
        WebSocketChannel.cache = cache;
    }

    @Autowired
    public void setUserTagService(UserTagService userTagService){
        WebSocketChannel.userTagService = userTagService;
    }


    @Autowired
    public void setUserService(UserService userService) {
        WebSocketChannel.userService = userService;
    }






    @Autowired
    public void setDeepSeekService(DeepSeekService deepSeekService) {
        WebSocketChannel.deepSeekService = deepSeekService;
    }

    @Autowired
    public void setTagService(TagService tagService){
        WebSocketChannel.tagService = tagService;
    }

    /***
     * 建立连接
     * @param session
     * @param userId
     */
    @OnOpen
    public void onOPen(Session session, @PathParam("userId") String userId){
        this.session = session;
        this.userId = userId;
        //获取user是否存在
//        User user = userService.getUserInfoById(userId);
        User user = userService.getUserInfoById(userId);
        if(user == null){
            try {
                this.session.close();
            } catch (IOException e) {
                throw new MyException("没有这个用户！");
            }
        }
        QueryWrapper<UserTag> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",userId);
        List<UserTag> userTags = userTagService.list(queryWrapper);
        System.out.println(userTags);
        List<DeepSeekRequest.Message> messages = new ArrayList<>();
        if(Objects.nonNull(userTags)){
            List<Integer> tagIds = userTags.stream().map(item -> {
                return item.getTagId();
            }).collect(Collectors.toList());
            List<Tag> tags = tagService.listByIds(tagIds);
            StringBuilder expertise = new StringBuilder();
            for(Tag item : tags){
                expertise.append(item.getDescription() + ",");
            }
            String noTags = "";
            // 2. 处理没有匹配标签的情况
            if (expertise.length() == 0) {
                noTags = "你是一个友好的助手，请与用户进行日常聊天";
                DeepSeekRequest.Message msg = new DeepSeekRequest.Message();
                msg.setRole("system");
                msg.setContent(noTags);
                messages.add(msg);
            }else {
                expertise.setLength(expertise.length() - 1); // 移除最后一个逗号
                String res = String.format(
                        "你是一个个性化的聊天助手，%s。请根据用户兴趣用中文进行自然交流，提供专业建议并保持互动趣味性。",
                        expertise.toString()
                );
                DeepSeekRequest.Message msg = new DeepSeekRequest.Message();
                msg.setRole("system");
                msg.setContent(res);
                messages.add(msg);
            }
        }
        chatHistoryHashMap.put(String.valueOf(user.getId()),messages);
        chatWebSocketHashMap.put(String.valueOf(user.getId()),this);
        onlineCount++;
        log.info("{}--连接",user.getName());
    }


    @OnClose
    public void onClose(){
        onlineCount--;
        log.info("断开连接");
//        log.info("{}--duanka",user.getName());
        chatWebSocketHashMap.remove(userId);
        System.out.println(chatWebSocketHashMap.get(userId));
    }


    @OnMessage
    public void onMessage(String message,Session session) throws IOException {
        List<DeepSeekRequest.Message> messages = chatHistoryHashMap.get(userId);
        Integer count = (Integer) cache.asMap().get(userId);
        if(count == null){
            cache.put(userId,1);
        }else {
            Integer c = count + 1;
            cache.put(userId,c);
        }
        String answer = deepSeekService.callDeepSeek(message,messages);
        sendInfo(answer,userId);
    }


    @OnError
    public void onError(Session session,Throwable error){
        error.printStackTrace();
    }


    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    public void sendInfo(String message,String toUserId) throws IOException {
        chatWebSocketHashMap.get(toUserId).sendMessage(message);
    }


    public void sendMessageToModel(String message){
        Qianfan qianfan = new Qianfan(Constrants.APP_KEY ,Constrants.APP_SECRET);
        // 指定模型
        qianfan.chatCompletion()
                .model(Constrants.MODEL)
                .addMessage("user", message)
                .execute();
    }


    public String getAnswer(String message){
        Qianfan qianfan = new Qianfan(Constrants.APP_KEY ,Constrants.APP_SECRET);
        // 指定模型
        ChatResponse resp = qianfan.chatCompletion()
                .model(Constrants.MODEL)
                .addMessage("user", message)
                .execute();
        return resp.getResult();
    }

}
